package cn.elwy.osgi.config;

import java.io.File;

import cn.elwy.osgi.config.util.ResourceUtil;

public class ConfigPath implements Constant {

  private static SubjectType SUBJECT_TYPE;

  static {
    try {
      ConfigPath.SUBJECT_TYPE = SubjectType.valueOf(ConfigContext.getSubjectType());
    } catch (Exception e) {
      ConfigPath.SUBJECT_TYPE = SubjectType.USER;
    }
  }

  private ConfigPath() {
  }

  /**
   * 获取主体对象的ID，根据主体的类型决定返回的是哪个对象的ID
   * @return
   */
  public static Object getSubjectId() {
    return getSubjectId(true);
  }

  /**
   * 获取主体对象的ID，根据主体的类型决定返回的是哪个对象的ID
   * @param state 是否返回主体对象的ID
   * @return
   */
  public static Object getSubjectId(Boolean state) {
    if (state == null || state == false) {
      return null;
    }
    Object subjectId = null;
    switch (SUBJECT_TYPE) {
      case USER:
        subjectId = ConfigContext.getSession().getUserId();
        break;
      case ROLE:
        subjectId = ConfigContext.getSession().getRoleId();
        break;
      case ORG:
        subjectId = ConfigContext.getSession().getOrgId();
        break;
      default:
        subjectId = ConfigContext.getSession().getUserId();
        break;
    }
    if (subjectId != null) {
      return SUBJECT_TYPE.toString() + "_" + subjectId;
    } else {
      return null;
    }
  }

  /**
   * 获取配置存储的路径
   * @param configDir 储存的目录
   * @param subjectId 主体的对象ID（user、role等的ID）
   * @param objectId 客体的对象ID（表格、对话框等的ID）
   * @param extName 存储的扩展名
   * @return
   */
  public static File getFile(String configDir, Object subjectId, String objectId, String extName) {
    String filePath = objectId + "." + extName;
    if (configDir == null || configDir.trim().isEmpty()) {
      configDir = "";
    } else {
      configDir = configDir + "/";
    }
    if (subjectId != null && subjectId.toString().trim().length() > 0) {
      filePath = CACHE_DIR + subjectId + "/" + configDir + filePath;
      return new File(ResourceUtil.getConfigHome(), filePath);
    } else {
      return new File(ResourceUtil.getConfigHome(), CACHE_DIR + configDir + filePath);
    }
  }

  /**
   * 获取配置存储的Key
   * @param configDir 储存的目录
   * @param subjectId 主体的对象ID（user、role等的ID）
   * @param objectId 客体的对象ID（表格、对话框等的ID）
   * @param extName 存储的扩展名
   * @return
   */
  public static String getStoreKey(String configDir, Object subjectId, String objectId, String extName) {
    String filePath = objectId + "_" + extName;
    if (subjectId != null && subjectId.toString().trim().length() > 0) {
      filePath = subjectId + "_" + configDir + "_" + filePath;
    } else {
      filePath = configDir + "_" + filePath;
    }
    return filePath;
  }

  public enum SubjectType {
    USER, ROLE, ORG;

    public String toString() {
      return name().toLowerCase();
    }
  }

}
